/*
 * Lesson基本信息编辑
 */
import * as React from 'react';
import { connect } from 'react-redux';
import { get, partial, invoke } from 'lodash';

import { getPanelOptions } from 'components/common/collapse';

import { Tooltip, Alert, Switch, Modal, Collapse, message, Row, Col, Button } from 'antd';

import './Edit.scss';
import { isLoading } from 'utils/utils';
import ACTIONS from 'constants/lesson';
import { fetchLessonDetail, removeLesson, updateLessonPublish } from 'actions/lesson';

import LoadableComponent from 'components/common/LoadableComponent';
const LoadableBasicEdit = LoadableComponent(() => import('./EditBasic'));
import EditAudio from './EditAudio';
import EditCover from './EditImage';
import EditThumb from './EditImage';

interface EditProps {
  dispatch: (action: any) => any;
  handleCallback: (id: number | null) => any;
  form: any;
  lessonId: number;
  courseId: number;
  loadingGroup: any;
  hasChanged: boolean;
}

interface EditState {
  activeKey: any;
  lessonDetail: any;
}

class Edit extends React.Component<EditProps, EditState> {
  steps: any[];
  RefEditAudio: any;
  RefEditCover: any;
  RefEditThumb: any;
  static collapseKeys = ['basic', 'audio', 'cover', 'thumb'];
  static defaultProps: EditProps = {
    dispatch: () => {},
    handleCallback: () => {},
    form: {},
    courseId: 0,
    lessonId: 0,
    loadingGroup: {},
    hasChanged: false,
  };
  constructor(props: EditProps) {
    super(props);

    this.state = {
      activeKey: Edit.collapseKeys,
      lessonDetail: null,
    };
  }

  componentDidMount() {
    if (this.props.lessonId) {
      this.handleFetchLessonDetail();
    }
  }

  componentWillReceiveProps(nextProps: any) {
    const { lessonId, hasChanged } = nextProps;
    const { lessonId: oldLessonId, hasChanged: oldHasChanged } = this.props;
    const { lessonDetail } = this.state;

    if (lessonId !== oldLessonId) {
      if (lessonId) {
        this.handleFetchLessonDetail(lessonId);
      } else {
        this.setState({
          lessonDetail: null,
        });
      }
    } else if (lessonDetail && hasChanged !== oldHasChanged) {
      const { isPublished } = lessonDetail;
      if (isPublished === 1 && hasChanged === true) {
        this.doPublish(lessonId, 2);
      }
    }
  }

  handleFetchLessonDetail = (lessonId: number = this.props.lessonId) => {
    const { dispatch, courseId } = this.props;

    dispatch(fetchLessonDetail(courseId, lessonId)).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        this.setState({
          lessonDetail: result.response.data,
        });
      }
    });
  };

  handleSwitchCollapse = (activeKey: any) => {
    this.setState({
      activeKey,
    });
  };

  handleBasicCallback = (newLessonId: number) => {
    this.props.handleCallback(newLessonId);
  };

  handleEditOtherCallback = () => {
    const { lessonId } = this.props;
    this.handleFetchLessonDetail(lessonId);
  };

  doPublish = (lessonId: number, status: number, callback = () => {}) => {
    const { dispatch, handleCallback } = this.props;
    dispatch(updateLessonPublish(lessonId, status)).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        message.success('保存成功');
        // 重新拉取数据，以便更新此课时的发布状态
        this.handleFetchLessonDetail(lessonId);
        handleCallback(lessonId);
      }
    });
  };

  // 课时发布开关
  handleLessonPublishSwitch = (checked: boolean) => {
    const { dispatch, lessonId, loadingGroup, handleCallback } = this.props;
    if (!lessonId || isLoading(loadingGroup, ACTIONS.UPDATE_PUBLISH_STATUS)) {
      return;
    }

    const status = Number(checked);
    const content = checked ? '课时上线' : '课时下线';
    Modal.confirm({
      title: '危险，慎重操作',
      content,
      okText: '确定',
      cancelText: '取消',
      iconType: 'info-circle',
      onOk: () => {
        this.doPublish(lessonId, status, () => {
          message.success('操作成功');
        });
      },
    });
  };

  // 删除课时
  handleRemove = () => {
    const { dispatch, courseId, lessonId, loadingGroup, handleCallback } = this.props;

    if (!lessonId || isLoading(loadingGroup, ACTIONS.REMOVE)) {
      return;
    }
    Modal.confirm({
      title: '危险',
      content: '你确定要删除此课时及其所有数据吗？',
      okText: '确定',
      cancelText: '取消',
      iconType: 'info-circle',
      onOk: () => {
        dispatch(removeLesson(courseId, lessonId)).then((result: any) => {
          if (result.code) {
            message.error(result.msg);
          } else {
            message.success('课时删除成功');
            handleCallback(null);
          }
        });
      },
    });
  };

  render() {
    const { courseId, lessonId, loadingGroup } = this.props;
    const { activeKey, lessonDetail } = this.state;
    const isPublished = Number(get(lessonDetail, 'isPublished', 0));
    const publishTip =
      isPublished === 0
        ? '当前课时未发布'
        : isPublished === 1
          ? '当前课时已经发布'
          : '当前课时已改动，请重新发布！';

    const collapseOptions: any = {
      activeKey,
      bordered: false,
      onChange: this.handleSwitchCollapse,
    };

    return (
      <React.Fragment>
        <Collapse {...collapseOptions}>
          <Collapse.Panel header="基本信息" key={Edit.collapseKeys[0]}>
            <LoadableBasicEdit
              courseId={courseId}
              lessonDetail={lessonDetail}
              handleCallback={this.handleBasicCallback}
            />
          </Collapse.Panel>
          <Collapse.Panel
            {...getPanelOptions(lessonId, '音频(标题)', {
              key: Edit.collapseKeys[1],
              addButton: true,
              onAdd: partial(invoke, this, 'RefEditAudio.addAudio'),
            })}>
            {lessonDetail && (
              <EditAudio
                lessonDetail={lessonDetail}
                handleCallback={this.handleEditOtherCallback}
                ref={(EditAudio: any) => {
                  this.RefEditAudio = EditAudio;
                }}
              />
            )}
          </Collapse.Panel>
          <Collapse.Panel
            {...getPanelOptions(lessonId, '图片(封面)', {
              key: Edit.collapseKeys[2],
              addButton: true,
              onAdd: partial(invoke, this, 'RefEditCover.addImage'),
            })}>
            {lessonDetail && (
              <EditCover
                type={0}
                courseId={courseId}
                lessonId={lessonDetail.id}
                lessonImage={lessonDetail.cover}
                handleCallback={this.handleEditOtherCallback}
                ref={(editImage: any) => {
                  this.RefEditCover = editImage;
                }}
              />
            )}
          </Collapse.Panel>
          <Collapse.Panel
            {...getPanelOptions(lessonId, '图片(缩略图)', {
              key: Edit.collapseKeys[3],
              addButton: true,
              onAdd: partial(invoke, this, 'RefEditThumb.addImage'),
            })}>
            {lessonDetail && (
              <EditThumb
                type={1}
                courseId={courseId}
                lessonId={lessonDetail.id}
                lessonImage={lessonDetail.thumbCover}
                handleCallback={this.handleEditOtherCallback}
                ref={(editImage: any) => {
                  this.RefEditThumb = editImage;
                }}
              />
            )}
          </Collapse.Panel>
        </Collapse>
        <Row align="middle" type="flex" justify="space-between" style={{ marginTop: 12 }}>
          <Col span={4}>
            <Tooltip title={publishTip}>
              <span>发布:&nbsp;</span>
              <Switch
                className={`publish-${isPublished}`}
                loading={isLoading(loadingGroup, ACTIONS.UPDATE_PUBLISH_STATUS)}
                checked={isPublished === 1}
                disabled={!lessonDetail}
                onChange={this.handleLessonPublishSwitch}
              />
            </Tooltip>
          </Col>
          <Col span={4} style={{ textAlign: 'right' }}>
            <Button
              loading={isLoading(loadingGroup, ACTIONS.REMOVE)}
              type="primary"
              className="ant-btn-danger"
              onClick={this.handleRemove}
              size="large"
              disabled={!lessonDetail}
              icon="delete">
              删除
            </Button>
          </Col>
        </Row>
        {isPublished === 2 && (
          <Alert
            style={{ position: 'fixed', top: 0, width: 450 }}
            message="请注意：当前课时已经改动，您必须重新进行发布！"
            type="warning"
            closable={true}
            showIcon={true}
          />
        )}
      </React.Fragment>
    );
  }
}

interface OwnProps {
  lessonId: number;
  courseId: number;
}

function mapStateToProps(state: any, ownProps: OwnProps) {
  const { courseId, lessonId } = ownProps;
  const { loadingGroup } = state;
  const { hasChanged } = state.lesson;

  return {
    loadingGroup,
    lessonId,
    courseId,
    hasChanged,
  };
}

export default connect(mapStateToProps)(Edit);
